//
//  MyDownLoadViewController.m
//  HuateVideo
//
//  Created by  on 12-5-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MyDownLoadViewController.h"
#import "ASIHTTPRequest.h"
#import "DownLoadingCell.h"
#import "UserDefaults.h"
#import "PicShowViewController.h"
#import "Movie.h"
@interface MyDownLoadViewController ()
@end

@implementation MyDownLoadViewController

-(void)cateArray{
    for (int i=0; i<downloadedArray.count; i++) {
        id m=[downloadedArray objectAtIndex:i];
        if ([m detailType]==MovieChannelTypeMusic) {
            [musicArray addObject:m];
        }else {
            [vidoeArray addObject:m];
        }
    }
}

#pragma mark btn envent
-(void)segmentChanged:(UISegmentedControl*)sender{
	if (sender.selectedSegmentIndex==0) {
        array=vidoeArray;
	}else {
        array=musicArray;
    }
    [finishedTable reloadData];

}


-(void)deleteMovie:(UIButton*)btn{
    id movie=[array objectAtIndex:btn.tag];
    NSString* storePath=[movie storePath];
    [[NSFileManager defaultManager] removeItemAtPath:storePath error:nil];
    [array removeObject:movie];
    [downloadedArray removeObject:movie];
    [UserDefaults setObject:downloadedArray forKey:DOWNLOADED_LIST];
    [finishedTable reloadData];
}
- (void)playMovie:(UIButton*)button{
    
	id temp = [array objectAtIndex:button.tag] ;
	if ([[temp Type] intValue] == MovieChannelTypePic) {
		PicShowViewController*picshow=[[PicShowViewController alloc] init];
		picshow.imgCount=0;
		picshow.picListArray=[NSArray arrayWithObject:temp];
		[self.navigationController pushViewController:picshow animated:YES];
		[picshow release];
	}
	else {
		if ([[temp Type] intValue] == MovieChannelTypeSeries) {
            
            NSMutableArray *tmp = [NSMutableArray array];
            for (int i=0; i<[[temp File_path_array] count]; i++) {
                if ([[[temp File_path_array] objectAtIndex:i] isKindOfClass:[NSString class]]) {
                    if ([[[temp File_path_array] objectAtIndex:i] length]>5) {
                        [tmp addObject:[[temp File_path_array] objectAtIndex:i]];
                    }
                }
            }
            [temp setFile_path_array:tmp];
            
            [temp setOrderNUM:0];
        }
		[[NSNotificationCenter defaultCenter] postNotificationName:PLAYMOVIENOTIFICATION object:temp];
	}
	
    
}
-(NSString*)destPath:(NSString*)filePath{
    NSString *destPath = [DOWNLOADED_VIDEOS_PATH stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[filePath lastPathComponent]]];
    return destPath;
}

-(double)readMovieSizeFromPath:(NSString*)filePath{
	BOOL b=[[NSFileManager defaultManager] fileExistsAtPath:[self destPath:filePath]];
    if (b) {
        NSDictionary* dic=[[NSFileManager defaultManager] attributesOfItemAtPath:[self destPath:filePath] error:nil];
		long long int filesize=[dic fileSize];
		double contentLength = (double)filesize/1024.0/1024.0;
		return contentLength;
    }
    return 0.0;
}

#pragma mark tableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString* Identifier = @"Identifier";
    DownLoadingCell* cell = (DownLoadingCell*)[tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil)
    {
        cell = [[[DownLoadingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier] autorelease];
    }
    Movie*fMov=[array objectAtIndex:indexPath.row];
    double size=[self readMovieSizeFromPath:[self destPath:[fMov File_path]]];
    cell.statelabel.text=LS(@"下载完成");
    cell.sizelabel.text=[NSString stringWithFormat:@"%@ %.1f M",LS(@"大小:"),size];
    cell.progressView.hidden=YES;
    cell.downloadTitle.text=[fMov News_title];
    cell.cellimage.image=[fMov iconImg];
    [cell.fabu setTitle:LS(@"播放") forState:UIControlStateNormal];
    [cell.shanchu setTitle:LS(@"删除") forState: UIControlStateNormal];
    cell.shanchu.tag=indexPath.row;
    cell.fabu.tag=indexPath.row;
    [cell.fabu addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shanchu addTarget:self action:@selector(deleteMovie:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark viewInit
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor=TOOLBAR_TINTCOLOR;
    UIBarButtonItem* but=[[UIBarButtonItem alloc] initWithTitle:LS(@"正在下载") style:UIBarButtonItemStylePlain target:self action:@selector(toDownloadingVC)];
    self.navigationItem.rightBarButtonItem=but;
    [but release];
}
-(void)toDownloadingVC{
    AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    app.mydownloadViewController.title=LS(@"正在下载");
    [self.navigationController pushViewController:app.mydownloadViewController animated:YES];
}
-(void)initTable{
	finishedTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320, 460-44-49-40) style:UITableViewStylePlain];
    finishedTable.tag=222;
    finishedTable.dataSource=self;
    finishedTable.delegate=self;
    finishedTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    finishedTable.backgroundColor=[UIColor clearColor];
    finishedTable.opaque=NO;
    finishedTable.allowsSelection=NO;
    [self.view addSubview:finishedTable];
    [finishedTable release];
	
}
- (void)initTopView
{
    segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:LS(@"视频"),LS(@"音乐"),nil]];
	segmentControl.frame = CGRectMake(10, 7, 140, 26);
    segmentControl.center=CGPointMake(160, 20);
    segmentControl.tintColor = TOOLBAR_TINTCOLOR;
	[segmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
	[segmentControl setSelectedSegmentIndex:0];
	[segmentControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
	[self.view addSubview:segmentControl];
	[segmentControl release];
    [self segmentChanged:segmentControl];
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 39, 320, 2)];
    line.image = [UIImage imageNamed:@"fengexian.png"];
    [self.view addSubview:line];
    [line release];
}

-(void)dealloc{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
    [musicArray release];
    [downloadedArray release];
    [vidoeArray release];
    [super dealloc];
}

- (void)finishedMovie:(NSNotification*)notify{
    id movie=[notify object];
    [downloadedArray addObject:movie];
    [UserDefaults setObject:downloadedArray forKey:DOWNLOADED_LIST];
    [self updateTable];
}

-(void)updateTable{
    [downloadedArray removeAllObjects];
    [downloadedArray addObjectsFromArray:[UserDefaults objectForKey:DOWNLOADED_LIST]];
    [self cateArray];
    [finishedTable reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(finishedMovie:)
													 name:DOWNLOADED_NOTIFICATION 
												   object:nil];

		downloadedArray=[[NSMutableArray alloc] initWithArray:[UserDefaults objectForKey:DOWNLOADED_LIST]];
        musicArray=[[NSMutableArray alloc] init];
        vidoeArray=[[NSMutableArray alloc] init];
		[self cateArray];
        [self initTable];
		[self initTopView];
	}
    return self;
}


@end
